package com.seeyon.apps.ndk.kit;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.seeyon.ctp.common.AppContext;
import com.seeyon.ctp.common.ctpenumnew.CtpEnumUtil;
import com.seeyon.ctp.common.exceptions.BusinessException;
import com.seeyon.ctp.common.log.CtpLogFactory;
import com.seeyon.ctp.common.po.ctpenumnew.CtpEnumItem;
import com.seeyon.ctp.common.po.ctpenumnew.CtpEnumItemPO;
import com.seeyon.ctp.organization.bo.V3xOrgAccount;
import com.seeyon.ctp.organization.bo.V3xOrgDepartment;
import com.seeyon.ctp.organization.bo.V3xOrgEntity;
import com.seeyon.ctp.organization.bo.V3xOrgMember;
import com.seeyon.ctp.organization.manager.OrgManager;
import com.seeyon.ctp.util.DBAgent;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.logging.Log;

import java.text.SimpleDateFormat;
import java.util.*;

public class DataConversionKit {

    private static final Log log = CtpLogFactory.getLog(DataConversionKit.class);

    private static OrgManager orgManager = (OrgManager) AppContext.getBean("orgManager");

    private static final String enumItemCode_fkfs = AppContext.getSystemProperty("ndk.enumItemCode.fkfs");
    private static final String enumItemCode_kmfplb = AppContext.getSystemProperty("ndk.enumItemCode.kmfplb");
    private static final String enumItemCode_xmlb = AppContext.getSystemProperty("ndk.enumItemCode.xmlb");

    /**
     * 对数据类型进行转换
     *
     * @param fieldType  字段类型
     * @param fieldValue 字段值
     * @return 转换后的值
     */
    public static Object dataConversion(String fieldType, Object fieldValue, String fieldDesc) throws Exception {
        Object value = "";
        String fieldValue_new = StrKit.str(fieldValue);
        if ("".equals(fieldValue_new)) {
            return "";
        }
        if ("imageselect".equals(fieldType) || "radio".equals(fieldType) || "select".equals(fieldType)) {
            if ("".equals(fieldValue_new)) {
                throw new BusinessException("枚举编码[" + fieldValue_new + "]在OA系统中未招到对应枚举");
            }
            //付款方式
            if ("ZLSCH".equals(fieldDesc)) {
                fieldValue_new = enumItemCode_fkfs + fieldValue_new;
            }
            if ("KNTTP".equals(fieldDesc)) {
                fieldValue_new = enumItemCode_kmfplb + fieldValue_new;
            }
            if ("PSTYP".equals(fieldDesc)) {
                fieldValue_new = enumItemCode_xmlb + fieldValue_new;
            }
            // 获取枚举项id
            CtpEnumItem ctpEnumItem = getItemByCode(fieldValue_new);
            if (ctpEnumItem != null) {
                value = ctpEnumItem.getId();
            } else {
                value = fieldValue_new;
            }
        } else if ("date".equals(fieldType)) {
            // 保留年月日时分秒
            if (!"".equals(fieldValue_new)) {
                if ("00000000".equals(fieldValue_new)) {
                    value = "";
                } else {
                    value = DateKit.getSimpleDate(fieldValue_new);
                }
            } else {
                value = fieldValue_new;
            }

        } else if ("checkbox".equals(fieldType)) {
            if ("1".equals(fieldValue_new)) {
                value = "勾选";
            } else {
                value = "未勾选";
            }
        } else if ("textarea".equals(fieldType) || "text".equals(fieldType) || "linenumber".equals(fieldType)) {
            value = fieldValue_new;
        } else if ("department".equals(fieldType)) {
            if (!"".equals(fieldValue_new)) {
                // 根据部门编码获取部门id
                List<V3xOrgEntity> orgDeptList = orgManager.getEntityList(V3xOrgDepartment.class.getSimpleName(), "code", fieldValue_new, null, false, true);
                if (!orgDeptList.isEmpty()) {
                    value = orgDeptList.get(0).getId();
                } else {
                    if ("".equals(value)) {
                        log.info("部门编码[" + fieldValue_new + "]在OA系统中未招到对应部门");
                        throw new BusinessException("部门编码[" + fieldValue_new + "]在OA系统中未招到对应部门");
                    }
                }
            }
        } else if ("account".equals(fieldType)) {
            if (!"".equals(fieldValue_new)) {
                // 根据单位编码获取单位id
                List<V3xOrgEntity> orgAccountList = orgManager.getEntityList(V3xOrgAccount.class.getSimpleName(), "code", fieldValue_new, null, false, true);
                if (!orgAccountList.isEmpty()) {
                    value = orgAccountList.get(0).getId();
                } else {
                    if ("".equals(value)) {
                        log.info("单位编码[" + fieldValue_new + "]在OA系统中未招到对应单位");
                        throw new BusinessException("单位编码[" + fieldValue_new + "]在OA系统中未招到对应单位");
                    }
                }
            }
        } else if ("multimember".equals(fieldType)) {
            String dataValue = fieldValue_new;
            if (!"".equals(dataValue)) {
                String[] dataArray = dataValue.split(",");
                StringBuilder stb = new StringBuilder();
                for (String id : dataArray) {
                    // 根据成员id获取成员名称
                    String name = orgManager.getMemberById(Long.parseLong(id)).getName();
                    stb.append(name).append(",");
                }
                value = stb.toString().substring(0, stb.toString().length() - 1);
            }
        } else if ("member".equals(fieldType)) {
            if (!"".equals(fieldValue_new)) {
                // 根据成员编码获取成员id
                List<V3xOrgEntity> orgMemberList = orgManager.getEntityList(V3xOrgMember.class.getSimpleName(), "code", fieldValue_new, null, false, true);
                if (!orgMemberList.isEmpty()) {
                    value = orgMemberList.get(0).getId();
                } else {
                    if ("".equals(value)) {
                        if ("ZZDR".equals(fieldDesc)) {
                            log.info("人员编码[" + fieldValue_new + "]在OA系统中未招到对应账号");
                            value = null;
                        } else {
                            log.info("人员编码[" + fieldValue_new + "]在OA系统中未招到对应账号");
                            throw new BusinessException("人员编码[" + fieldValue_new + "]在OA系统中未招到对应账号");
                        }
                    }
                }
            }
        } else if ("datetime".equals(fieldType)) {
            // 将时间戳转换为yyyy-MM-dd HH:mm:ss格式
            value = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format((Date) fieldValue);
        } else {
            value = fieldValue_new;
        }
        return value;
    }


    /**
     * 根据成员登录名和账号ID获取兼职的对应单位部门ID
     *
     * @param tokenId         令牌
     * @param memberUrl       成员URL
     * @param memberLoginName 成员登录名
     * @param jsonArray       JSON数组
     * @return 部门ID
     * @throws Exception 异常
     */
    public static String getDeptIdByMemberLoginNameAndAccountId(String tokenId, String memberUrl, String memberLoginName, JSONArray jsonArray) throws Exception {
        log.info("tokenId:" + tokenId);
        String deptId = "";
        String accountCode = "";
        if (!jsonArray.isEmpty()) {
            for (int i = 0; i < jsonArray.size(); i++) {
                JSONObject jsonObject = jsonArray.getJSONObject(i);
                String fieldName = StrKit.str(jsonObject.get("fieldName"));
                String fieldValue = StrKit.str(jsonObject.get("fieldValue"));
                if ("BUKRS".equals(fieldName)) {
                    accountCode = fieldValue;
                }
            }
        }
        log.info("单位编码:" + accountCode);
        String accountId = "";
        if (!"".equals(accountCode)) {
            List<V3xOrgEntity> orgAccountList = orgManager.getEntityList(V3xOrgAccount.class.getSimpleName(), "code", accountCode, null, false, true);
            if (!orgAccountList.isEmpty()) {
                accountId = StrKit.str(orgAccountList.get(0).getId());
            }
        }
        V3xOrgMember v3xOrgMember = null;
        if (!"".equals(memberLoginName)) {
            v3xOrgMember = orgManager.getMemberByLoginName(memberLoginName);
        }
        String memberId = "";
        if (v3xOrgMember != null) {
            memberId = StrKit.str(v3xOrgMember.getId());
        }
        if (!"".equals(memberId)) {
            String memberUrl_new = memberUrl + memberId;
            Map<String, Object> headers = new HashMap<String, Object>();
            headers.put("token", tokenId);
            String result = HttpKit.get(memberUrl_new, headers);
            if (result.contains("concurrent_post")) {
                JSONObject resultObj = JSONObject.parseObject(result);
                JSONArray accountArray = resultObj.getJSONArray("concurrent_post");
                if (accountArray.size() > 0) {
                    for (int j = 0; j < accountArray.size(); j++) {
                        JSONObject accountObject = accountArray.getJSONObject(j);
                        String orgAccountId = StrKit.str(accountObject.get("orgAccountId"));
                        if (accountId.equals(orgAccountId)) {
                            deptId = StrKit.str(accountObject.get("depId"));
                            break;
                        } else {
                            deptId = StrKit.str(v3xOrgMember.getOrgDepartmentId());
                        }
                    }
                } else {
                    deptId = StrKit.str(v3xOrgMember.getOrgDepartmentId());
                }
            }
        }
        return deptId;
    }

    public static CtpEnumItem getItemByCode(String enumItemCode) throws BusinessException {
        String hql =  " select " + CtpEnumUtil.newCtpEnumItemHql +  "from " + CtpEnumItemPO.class.getName() + " f where f.enumItemCode=:enumItemCode";
        Map<String, Object> map = new HashMap<String, Object>();
        map.put("enumItemCode", enumItemCode);
        List list = DBAgent.find(hql, map);
        if (CollectionUtils.isNotEmpty(list)) {
            return (CtpEnumItem) list.get(0);
        }
        return null;
    }

}
